package service

import (
	"context"
	"encoding/json"
	"fmt"
	"kim/config"
	"kim/entity"
	"kim/model"
	"strconv"
	"time"
)

// 通过MongoDB 持久化消息

func InsertMsg(data []byte, isReaded bool) {

	msg := &entity.Message{}
	_ = json.Unmarshal(data, &msg)

	record := &model.Record{
		Userid:     msg.Userid,
		Dstid:      msg.Dstid,
		Content:    msg.Content,
		CreateTime: time.Now(),
		IsReaded:   isReaded,
		Cmd:        msg.Cmd,
	}
	id := strconv.Itoa(int(msg.Userid))

	collection := config.MongoDBClient.Database("kim").Collection(id)

	_, err := collection.InsertOne(context.TODO(), record)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("消息持久化完成")
	return
}

//插入离线消息
func InsertOffLineMsg(data []byte) {
	msg := &entity.Message{}

	_ = json.Unmarshal(data, &msg)

	record := &model.OffRecord{
		DstId:      msg.Dstid,
		UserId:     msg.Userid,
		Content:    msg.Content,
		CreateTime: time.Now(),
	}

	result := config.DB.Create(&record)

	fmt.Println("离线消息持久化完成")
	if result.Error != nil {
		fmt.Println(result.Error)
	}

}

func GetOffLineRecordsByUserId(userId int64) []model.OffRecord {

	queryWrapper := &model.OffRecord{
		DstId: userId,
	}

	offLineRecords := []model.OffRecord{}

	config.DB.Where(queryWrapper).Find(&offLineRecords)

	//TODO  删除
	config.DB.Where(queryWrapper).Delete(model.OffRecord{})

	return offLineRecords

}
